<?php

/**
 * 仓库设置管理ajax类
 * @package  ajax
 * @subpackage  backend
 * @create by allen.qiang
 */
quanli_require('module/base/wmsHandler.class.php');
quanli_require('module/base/goodsHandler.class.php');

class ajax_store {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //获取仓库列表
                    $this->storeList();
                    break;

                case 2: //对仓库更新或保存
                    $this->updateStore();
                    break;

                case 3: //仓库默认 设置
                    $this->changeDefault();
                    break;

                case 4: //仓库区域添加或编辑
                    $this->storeRegionAdd();
                    break;

                case 5: //城市联动
                    $this->cityChange();
                    break;

                case 6: //删除仓库
                    $this->deleteStore();
                    break;

                case 7: //仓库库位列表
                    $this->storeShelfList();
                    break;

                case 8: //仓库库位添加或编辑
                    $this->storeShelfAdd();
                    break;

                case 9: //删除仓库
                    $this->storeShelfDelete();
                    break;

                case 10: //批量添加货位
                    $this->batchShelf();
                    break;

                case 11: //检查商品货位是否存在
                    $this->checkShelfName();
                    break;

                case 12: //绑定商品与货位
                    $this->bindShelf();
                    break;

                case 13: //货位管理列表
                    $this->shelfManage();
                    break;

                case 14: //解除库位绑定
                    $this->cancel_shelfBind();
                    break;

            }

        }

    }

    /**
     * 获取仓库列表
     */
    private function storeList() {

        global $G_PGLOB;

        $page        = $_REQUEST['page'];
        $rp          = $_REQUEST['rp'];

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //组装查询条件数组
        $search_arr = array();

        //查询条件类型
        $search_type = '';

        //查询SQL
        $search_string = '';

        //排序
        $sql_sequee = sprintf(" ORDER BY %s %s ",$_REQUEST['sortname'],$_REQUEST['sortorder']);

        //分页
        $limit =  $sql_sequee . ' LIMIT ' . ($page-1)*$rp . ',' . $rp;

        try {

            //查询总数
            $sqlcount = "SELECT count(*) num FROM wms_store " . $search_string;
            $sqlcount_result = $G_PGLOB->DBCA->stmt_query($sqlcount);

            //查询数据
            $sql = 'SELECT * FROM wms_store ' . $search_string . $limit;
            $result  =  $G_PGLOB->DBCA->stmt_query($sql);

            //组织返回的数据
            $result_array = array(
                'page'  => $_REQUEST['page'],
                'total' => $sqlcount_result[0]->num,
                'rows'  => array()
            );

            if( $result ){

                foreach ( $result as $key=>$value){

                    //连接配送区域字符串
                    $regionString = '';

                    //查询配送区域
                    $searchregion = array(
                        'storeID'=>$value->storeID
                    );
                    $storeRegion = $commHandler->search( $searchregion , 'wms_store_region' );

                    if( $storeRegion ){

                        foreach ( $storeRegion as $k=>$val ){

                            //查询配送区域的名称
                            $regionSearch = array('id'=>$val->regionID);
                            $regionList = $commHandler->search($regionSearch,'sys_region');

                            //超过八个记录就换行
                            if(  $k != 0 && ($k+1) % 9 == 0 ){

                                //连接字符串
                                $regionString .= ',<br>' . $regionList[0]->name;

                            }else{

                                //连接字符串
                                $regionString .= ',' . $regionList[0]->name;

                            }

                        }

                    }

                    if( $regionString != '' ){
                        $regionString = substr($regionString,1);
                    }

                    //是否默认
                    if( $value->isdefault == 1 ){
                        $isDefault = '是';
                    }else{
                        $isDefault = '<a href="javascript:void(0);" onclick="store.changeDefault(' . $value->storeID . ',\'' . $value->storeName . '\')">否</a>';
                    }

                    if( $G_PGLOB->has_permission(6007) ){

                        $result_array['rows'][$key] = array(
                            'id' => $value->storeID,
                            'cell' => array(
                                '<a href="javascript: void(0);" onclick="store.edit(' . $value->storeID . ');" >修改</a>&nbsp;&nbsp;'.
                                '<a href="javascript: void(0);" onclick="store.region(' . $value->storeID . ');" >区域</a>&nbsp;&nbsp;',
                                $isDefault,
                                $value->priority,
                                $value->storeNo,
                                $value->storeName,
                                $value->provinceName.' '.$value->cityName.' '.$value->regionName.' '.$value->address,
                                $value->linkman,
                                $value->phone,
                                $value->mobile,
                                $regionString
                            )
                        );

                    } else {

                        $result_array['rows'][$key] = array(
                            'id' => $value->storeID,
                            'cell' => array(
                                $value->storeNo,
                                $value->storeName,
                                $regionString
                            )
                        );

                    }

                }

            }

            echo json_encode($result_array);
            return;

        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }

    }

    /**
     * 对仓库进行编辑或保存
     */
    private function updateStore() {

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeNo     = $_REQUEST['storeNo'];      //仓库编号
        $storeID     = $_REQUEST['storeID'];      //仓库ID
        $storeName   = $_REQUEST['storeName'];   //仓库名称
        $priority    = $_REQUEST['priority'];    //优先级
        $linkman     = $_REQUEST['linkman'];     //联系人
        $provinceID  = $_REQUEST['provinceID'];  //省份ID
        $cityID      = $_REQUEST['cityID'];      //城市ID
        $regionID    = $_REQUEST['regionID'];    //区域ID
        $address     = $_REQUEST['address'];     //地址
        $mobile      = $_REQUEST['mobile'];      //手机
        $phone       = $_REQUEST['phone'];       //电话
        $postCode    = $_REQUEST['postCode'];    //邮编
       $description = $_REQUEST['description'];  //描述
        $isdefault  = $_REQUEST['default'];      //仓库默认标志

        //字符处理
        $storeName   = $commHandler->getVal($storeName);
        $description = $commHandler->getVal($description);
        $address     = $commHandler->getVal($address);

        if( $mobile != '' && !$commHandler->isMobile( $mobile ) ){
            die( json_encode( array( 'code'=>400 , 'message'=>'手机号码格式有误' ) ) );
        }

        if( $phone != '' && !$commHandler->isPhone( $phone ) ){
            die( json_encode( array( 'code'=>400 , 'message'=>'电话号码格式有误' ) ) );
        }

        if( $mobile == '' && $phone == '' ){
            die( json_encode( array( 'code'=>400 , 'message'=>'手机和电话至少填写一项' ) ) );
        }

        $store_obj = new entity('wms_store');

        if( !empty($storeID) ){

            $store_obj->storeID = $storeID;

            if( !$G_PGLOB->DBCA->fetch($store_obj) ){
                echo json_encode( array('message'=>'没有找到当前信息' , 'code'=>404 ) );
                return;
            }

            //检查优先级是否重复
            $check_priority = new entity('wms_store');
            $check_priority->priority = $priority;

            if( $G_PGLOB->DBCA->fetch($check_priority) && $check_priority->storeID != $storeID )
                die( json_encode( array('message'=>'优先级已存在' , 'code'=>404 ) ) );

        }else{

            //检查优先级是否重复
            $check_priority = new entity('wms_store');
            $check_priority->priority = $priority;

            if( $G_PGLOB->DBCA->fetch($check_priority) )
                die( json_encode( array('message'=>'优先级已存在' , 'code'=>400 ) ) );

            $store_obj->creator = $G_PGLOB->currentUserID;

        }

        //查询区域信息
        $sys_region_sql = 'SELECT * FROM sys_region WHERE id=?';

        //获取省份信息
        $provinceInfo = $G_PGLOB->DBCA->stmt_query( $sys_region_sql , 'i' ,  $provinceID);

        if( empty($provinceInfo) ){
            die( json_encode( array( 'code'=>404 , 'message'=>'地区信息有误' ) ) );
        }

        //获取省份信息
        $cityInfo = $G_PGLOB->DBCA->stmt_query( $sys_region_sql , 'i' ,  $cityID);

        if( empty($cityInfo) ){
            die( json_encode( array( 'code'=>404 , 'message'=>'地区信息有误' ) ) );
        }

        //获取省份信息
        $regionInfo = $G_PGLOB->DBCA->stmt_query( $sys_region_sql , 'i' ,  $regionID);

        if( empty($regionInfo) ){
            die( json_encode( array( 'code'=>404 , 'message'=>'地区信息有误' ) ) );
        }

        $store_obj->storeName    = $storeName;
        $store_obj->storeNo      = $storeNo;
        $store_obj->priority     = $priority;
        $store_obj->linkman      = $linkman;
        $store_obj->mobile       = $mobile;
        $store_obj->phone        = $phone;
        $store_obj->postCode     = $postCode;
        $store_obj->provinceID   = $provinceID;
        $store_obj->provinceName = $provinceInfo[0]->name;
        $store_obj->cityID       = $cityID;
        $store_obj->cityName     = $cityInfo[0]->name;
        $store_obj->regionID     = $regionID;
        $store_obj->regionName   = $regionInfo[0]->name;
        $store_obj->address      = $address;
        $store_obj->description  = $description;
        $store_obj->isdefault    = $isdefault;

        //查询出该仓库名为“$storeName”的所有信息
        $checkNo_sql = 'SELECT * from wms_store WHERE storeName=?';
        $checkNo_result = $G_PGLOB->DBCA->stmt_query($checkNo_sql,'s',$storeName);

        //检查该仓库名下该编号是否已经存在
        if( $checkNo_result ){

            if( $storeID ){

                //编辑状态下，若循环到当前编辑对象则跳过
                foreach( $checkNo_result as $v1 ){

                    //如果是当前编辑的对象，则跳过
                    if( $storeID == $v1->storeID )
                        continue;

                    if( $storeNo == $v1->storeNo ){
                        echo json_encode( array('message'=>'编号重复' , 'code'=>400 ) );
                        return;
                    }

                }

            }else{

                //新增时，检查该仓库中有没有与所填编号相同的编号
                foreach( $checkNo_result as $v1 ){

                    if( $storeNo == $v1->storeNo ){
                        echo json_encode( array('message'=>'编号重复' , 'code'=>400 ) );
                        return;
                    }

                }

            }

        }


        //将其他仓库取消默认
        $cancel_default = 'UPDATE wms_store SET isdefault = ? WHERE storeID != ?';

        //新增状态下，若设置此新增仓库为默认仓库，则先将之前存在的所有仓库“默认”字段设置为“0”
        $cancel_default_all = 'UPDATE wms_store SET isdefault = ?';

        try{

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            if( $storeID ){

                //编辑时，如果该仓库设置为默认，则将其他仓库的默认仓库字段设置为“0”
                if( $isdefault == 1 ){
                    $G_PGLOB->DBCA->stmt_query($cancel_default,'ii',array(0,$storeID));
                }

            }else{

                //新增状态下，若设置此新增仓库为默认仓库，则先将之前存在的所有仓库默认字段设置为“0”
                if( $isdefault == 1 ){
                    $G_PGLOB->DBCA->stmt_query($cancel_default_all,'i',0);
                }

            }

            $G_PGLOB->DBCA->save( $store_obj );

            $G_PGLOB->DBCA->commit();

            if( $storeID ){
                echo json_encode( array('message'=>'更新成功' , 'code'=>200 ) );
                return;
            }else{
                echo json_encode( array('message'=>'保存成功' , 'code'=>200 ) );
                return;
            }


        }catch(Exception $e){
            $G_PGLOB->DBCA->rollBack();
            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
            return;
        }




    }

    /**
     * 仓库默认设置
     */
    function changeDefault(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler($G_PGLOB->DBCA);

        //获取参数
        $storeID = $_REQUEST['storeID'];

        //查询该仓库是否存在
        $storeExistArr = array('storeID'=>$storeID);
        $storeExist    = $commHandler->search($storeExistArr,'wms_store');

        if( empty($storeExist) ){
            echo json_encode( array('message'=>'没有找到该仓库信息' , 'code'=>404) );
            return;
        }

        //将当前仓库设置为默认
        $default = 'UPDATE wms_store SET isdefault = ? WHERE storeID = ?';

        //将其他仓库取消默认
        $cancel_default = 'UPDATE wms_store SET isdefault = ? WHERE storeID != ?';

        try{

            $G_PGLOB->DBCA->beginTransaction();

            //设置当前仓库为默认
            $G_PGLOB->DBCA->stmt_query($default,'ii',array(1,$storeID));

            $G_PGLOB->DBCA->stmt_query($cancel_default,'ii',array(0,$storeID));

            $G_PGLOB->DBCA->commit();

            echo json_encode( array('message'=>'设为默认成功' , 'code'=>200) );
            return;

        }catch( Exception $e ){
            $G_PGLOB->DBCA->rollBack();
            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，操作失败' , 'code'=>500) );
            return;
        }


    }

    /**
     * 添加或编辑仓库区域
     */
    private function storeRegionAdd(){

        global $G_PGLOB;

        //获取参数
        $storeID   = $_REQUEST['storeID'];
        $editFlg   = $_REQUEST['editFlg'];

        //先将该仓库原区域信息删除
        $deleteSQL = 'DELETE FROM wms_store_region WHERE storeID=?';

        try {

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            $G_PGLOB->DBCA->stmt_query($deleteSQL,'i',$storeID);

            //保存区域信息
            foreach ( $_REQUEST['params'] as $value ){

                $region_obj = new entity('wms_store_region');
                $region_obj->storeID = $storeID;
                $region_obj->regionID = $value['id'];

                //查询该区域ID的等级
                $level_sql = 'SELECT region_level FROM sys_region WHERE id=?';
                $level     = $G_PGLOB->DBCA->stmt_query($level_sql,'i',$value['id']);

                $region_obj->creator = $G_PGLOB->currentUserID;
                $region_obj->levelFlg = $level[0]->region_level;

                $G_PGLOB->DBCA->save( $region_obj );

            }

            //提交事务
            $G_PGLOB->DBCA->commit();

            if( $editFlg == 1 ){
                echo json_encode( array( 'message'=>'更新成功' , 'code'=>200 ) );
            }else{
                echo json_encode( array( 'message'=>'保存成功' , 'code'=>200 ) );
            }

            return;

        }catch (Exception $e){

            //回滚事务
            $G_PGLOB->DBCA->rollBack();
            error_log( $e->getMessage() );
            echo json_encode( array( 'message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
            return;
        }

    }

    /**
     * 城市联动
     */
    function cityChange(){

        global $G_PGLOB;

        /**
         * 获取参数
         * $flg   1:选取城市   2：选取区
         */
        $id = $_REQUEST['id'];
        $flg = $_REQUEST['flg'];

        //查询语句
        $sql_search = 'SELECT id,name,parentID,region_level FROM sys_region WHERE parentID=? AND region_level=?';

        if( $flg == 1 ){

            $result = $G_PGLOB->DBCA->stmt_query($sql_search , 'ii' , array($id , 2) );

        }else{

            $result = $G_PGLOB->DBCA->stmt_query($sql_search , 'ii' , array($id , 3) );

        }

        $params = array();

        if( $result ){

            foreach ( $result as $value ){
                $params[] = array( 'id'=>$value->id , 'name'=>$value->name );
            }

        }

        echo json_encode( array( 'code'=>200 , 'data'=>$params) );
        return;
    }

    //删除仓库
    function deleteStore(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        /**接收参数
         *
         * $_REQUEST[delArr] => Array(
        [0] => 19
        [1] => 18
        [2] => 17
        )
         *这是由要删除的仓库ID组成的数组
         */
        $delArr = $_REQUEST['delArr'];

        //删除仓库
        $del_store = 'DELETE FROM wms_store WHERE storeID=?';

        //删除该仓库下的区域
        $del_store_region = 'DELETE FROM wms_store_region WHERE storeID=?';

        //删除该仓库的库位信息
        $del_store_shelf = 'DELETE FROM wms_store_shelf WHERE storeID=?';

        //统计不存在的仓库的数目
        $errorNum_store = 0;
        $errorArr = array();

        if( $delArr ){

            //检查要删除的仓库是否全部存在
            foreach( $delArr as $value ){

                //检查仓库是否存在
                $checkArr = array('storeID'=>$value);
                $result   = $commHandler->search($checkArr,'wms_store');

                if( !$result ){
                    $errorArr[] = $value;
                    $errorNum_store++;
                }

            }

            if( $errorNum_store > 0 ){

                echo json_encode( array('message'=>'所选部分仓库已不存在，请刷新页面' , 'code'=>400 ) );
                return;

            }else{

                try{

                    //开启事务
                    $G_PGLOB->DBCA->beginTransaction();

                    //循环删除
                    foreach( $delArr as $value ){

                        //删除仓库
                        $G_PGLOB->DBCA->stmt_query($del_store,'i',$value);

                        //删除仓库区域
                        $G_PGLOB->DBCA->stmt_query($del_store_region,'i',$value);

                        //删除库位信息
                        $G_PGLOB->DBCA->stmt_query($del_store_shelf,'i',$value);

                    }

                    //提交事务
                    $G_PGLOB->DBCA->commit();

                    echo json_encode( array('message'=>'删除成功', 'code'=>200) );
                    return;

                }catch( Exception $e ){

                    $G_PGLOB->DBCA->rollBack();
                    error_log($e->getMessage());
                    echo json_encode( array('message'=>'系统错误，请与管理员联系', 'code'=>500) );
                    return;

                }

            }

        }else{

            echo json_encode( array('message'=>'请选择要删除的仓库' , 'code'=>400 ) );
            return;

        }

    }

    //仓库库位列表
    function storeShelfList(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID     = isset($_REQUEST['storeID']) && $_REQUEST['storeID'] != -1  ? $_REQUEST['storeID'] : null;
        $shelf_name  = trim($_REQUEST['shelf_name']);
        $page        = $_REQUEST['page'];
        $rp          = $_REQUEST['rp'];

        //组装查询条件数组
        $search_arr = array();

        //查询条件类型
        $search_type = '';

        //查询SQL
        $search_string = '';

        if( !empty( $storeID ) ){
            $search_string .= ' AND wss.storeID=?';
            $search_type   .= 'i';
            $search_arr[] = $storeID;
        }

        if( !empty( $shelf_name ) ){
            $search_string .= ' AND wss.shelf_name like ?';
            $search_type   .= 's';
            $search_arr[] = '%'.$shelf_name.'%';
        }

        if( $search_string ){
            $search_string = ' WHERE ' . substr( $search_string , 4 );
        }

        try {

            //排序
            $sql_sequee = sprintf(" ORDER BY %s %s ",$_REQUEST['sortname'],$_REQUEST['sortorder']);

            //分页
            $limit =  $sql_sequee . ' LIMIT ' . ($page-1)*$rp . ',' . $rp;

            //查询总数
            $sqlcount = "SELECT count(*) num FROM wms_store_shelf wss INNER JOIN wms_store ws ON wss.storeID = ws.storeID " . $search_string;
            $sqlcount_result = $G_PGLOB->DBCA->stmt_query($sqlcount,$search_type,$search_arr);

            //查询数据
            $sql = 'SELECT ws.storeID,ws.storeName,wss.shelfID,wss.shelf_name
                  FROM wms_store_shelf wss INNER JOIN wms_store ws ON wss.storeID = ws.storeID ' . $search_string . $limit;
            $result  =  $G_PGLOB->DBCA->stmt_query($sql,$search_type,$search_arr);

            //组织返回的数据
            $result_array = array(
                'page'  => $_REQUEST['page'],
                'total' => $sqlcount_result[0]->num,
                'rows'  => array()
            );

            if( $result ){

                foreach ( $result as $key=>$value){

                    $result_array['rows'][$key] = array(
                        'id' => $value->storeID."_".$value->shelfID,
                        'cell' => array(
                            '<a href="javascript: void(0);" onclick="storeShelf.edit(' . $value->storeID . ',' . $value->shelfID .');" >修改</a>',
                            $value->storeName,
                            $value->shelfID,
                            $value->shelf_name
                        )
                    );

                }


            }

            echo json_encode($result_array);
            return;
        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }

    }

    //编辑或添加货位
    function storeShelfAdd(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID = $_REQUEST['storeID'];
        $shelfID = $_REQUEST['shelfID'];

        //查询仓库信息
        $storeArr = array('storeID'=>$storeID);
        $storeInfo = $commHandler->search($storeArr,'wms_store');

        if( empty($storeInfo) ){
            echo json_encode( array('message'=>'没有找到对应仓库信息' , 'code'=>404 ) );
            return;
        }

        //校验该库位号在此仓库中是否已存在
        $checkShelfObj = new entity('wms_store_shelf');
        $checkShelfObj->storeID    = $storeID;
        $checkShelfObj->shelf_name = $_REQUEST['shelf_name'];

        if( $shelfID ){

            if( $G_PGLOB->DBCA->fetch($checkShelfObj) ){

                if(  $checkShelfObj->shelfID != $shelfID ){
                    echo json_encode( array('message'=>'该货位号['.$_REQUEST['shelf_name'].']已存在','code'=>400) );
                    return;
                }

            }

        }else{

            if( $G_PGLOB->DBCA->fetch($checkShelfObj) ){
                echo json_encode( array('message'=>'该货位号['.$_REQUEST['shelf_name'].']已存在','code'=>400) );
                return;
            }

        }

        $storeShelfObj = new entity('wms_store_shelf');
        $storeShelfObj->storeID = $storeID;
        $storeShelfObj->shelfID = $shelfID;

        if( !empty($shelfID) ){

            if(!$G_PGLOB->DBCA->fetch($storeShelfObj)){
                echo json_encode( array('message'=>'没有找到该货位信息','code'=>404) );
                return;
            }

        }

        $storeShelfObj->shelf_name = $_REQUEST['shelf_name'];


        try{

            $G_PGLOB->DBCA->save($storeShelfObj);

            if( !empty($shelfID) ){
                echo json_encode( array('message'=>'编辑成功','code'=>200) );
            }else{
                echo json_encode( array('message'=>'保存成功','code'=>200) );
            }

            return;

        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'保存成功','code'=>200) );
            return;
        }

    }

    /**
     * 删除货位
     * $_POST['store_array']  = array(
                key => array (storeID,shelfID)
     *          ...
     * )
     */
    function storeShelfDelete(){

        global $G_PGLOB;

        if(!isset($_REQUEST['store_array']) || empty($_REQUEST['store_array']) ){
            die( json_encode( array('code'=>400 , 'message' => '请选择要删除的货位') ) );
        }

        $wms_store_shelf_obj = array();     //货位表数据
        foreach ($_REQUEST['store_array'] as $value){
            $wms_store_shelf = new entity('wms_store_shelf');
            $wms_store_shelf->storeID = $value[0];
            $wms_store_shelf->shelfID = $value[1];
            if(!$G_PGLOB->DBCA->fetch($wms_store_shelf)){
                die( json_encode( array('code' => 404 ,'message' => sprintf("编号[%d]的货位已不存在，请刷新页面",$value[1])) ) );
            }
            $wms_store_shelf_obj[] = $wms_store_shelf;
        }

        $sql = "DELETE FROM wms_store_shelf_goods WHERE storeID = ? AND shelfID = ?";

        try{

            $G_PGLOB->DBCA->beginTransaction();

            foreach ($wms_store_shelf_obj as $obj){
                //删除货位与商品映射
                $G_PGLOB->DBCA->stmt_query($sql,'ii',$obj->storeID,$obj->shelfID);

                //删除货位
                $G_PGLOB->DBCA->delete($obj);
            }

            $G_PGLOB->DBCA->commit();
            echo json_encode(array('code' => 200 , 'message' => '删除成功'));
        }catch (Exception $e){
            $G_PGLOB->DBCA->rollBack();
            error_log($e->getMessage());
            echo json_encode(array('code' => 500 , 'message' => '系统错误，删除失败'));
        }
        return;
    }

    //批量生产库位号
    private function batchShelf(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID = $_REQUEST['storeID'];  //仓库ID
        $prefix = $_REQUEST['prefix'];  //前缀
        $suffix = $_REQUEST['suffix'];  //后缀
        $number = $_REQUEST['number'];  //数量

        //查询仓库信息
        $storeArr = array('storeID'=>$storeID);
        $storeInfo = $commHandler->search($storeArr,'wms_store');

        if( empty($storeInfo) ){
            echo json_encode( array('message'=>'没有找到对应仓库信息' , 'code'=>404 ) );
            return;
        }

        if( $number == 0 ){
            echo json_encode( array('message'=>'请输入大于0的正整数' , 'code'=>400 ) );
            return;
        }

        //保存对象数组
        $params = array();

        for( $i=1; $i<=$number; $i++ ){

            $wms_shelf = new entity('wms_store_shelf');
            $wms_shelf->storeID    = $storeID;
            $wms_shelf->shelf_name = $prefix . $i . $suffix;

            if( $G_PGLOB->DBCA->fetch($wms_shelf) ){
                continue;
            }

            $params[] = $wms_shelf;

        }

        try{

            if( $params ){

                //开启事务
                $G_PGLOB->DBCA->beginTransaction();

                foreach( $params as $obj ){
                    $G_PGLOB->DBCA->save( $obj );
                }

                //提交事务
                $G_PGLOB->DBCA->commit();

            }

            echo json_encode( array('message'=>'批量生成库位号成功' , 'code'=>200 ) );
            return;

        }catch(Exception $e){

            if( $params ){
                //回滚事务
                $G_PGLOB->DBCA->rollBack();
            }
            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，批量生产库位号失败' , 'code'=>500 ) );
            return;

        }

    }

    //检查货位号是否正确
    function checkShelfName(){

        global $G_PGLOB;

        //接收参数
        $storeID    = $_REQUEST['storeID'];  //仓库ID
        $shelf_name = $_REQUEST['shelf_name'];

        $wms_shelf = new entity('wms_store_shelf');
        $wms_shelf->storeID    = $storeID;
        $wms_shelf->shelf_name = $shelf_name;

        if( !$G_PGLOB->DBCA->fetch($wms_shelf) ){
            echo json_encode( array('message'=>'该货位号不存在' , 'code'=>404 ) );
            return;
        }

        echo json_encode( array('message'=>'' , 'code'=>200 ) );
        return;

    }

    //检查商品信息
    function checkGoods(){

        global $G_PGLOB;

        //接收参数
        $goodsType    = $_REQUEST['goodsType'];
        $goods = $_REQUEST['goods'];

        /**
         * $goodsType  查询类型
         * 1：商品号(product_code)  2：条形码(barcode)
         */
        if( $goodsType == 1 ){

            $checkSql = 'SELECT * FROM goods_sale WHERE product_code = ?';

        }else{

            $checkSql = 'SELECT * FROM goods_sale WHERE barcode = ?';

        }

        $result = $G_PGLOB->DBCA->stmt_query($checkSql,'s',$goods);

        if( empty($result) ){
            echo json_encode( array('message'=>'没有找到商品信息' , 'code'=>404 ) );
            return;
        }

        echo json_encode( array('message'=>'' , 'code'=>200 ) );
        return;

    }

    //绑定商品与货位
    function bindShelf(){

        global $G_PGLOB;

        //接收参数
        $storeID    = $_REQUEST['storeID'];  //仓库ID
        $shelf_name = $_REQUEST['shelf_name'];  //货位号
        $amount    = isset($_REQUEST['amount'])?$_REQUEST['amount']:0;  //上架数量
        $goods = $_REQUEST['goods'];            //商品product_code


        //查询货位信息
        $wms_shelf = new entity('wms_store_shelf');
        $wms_shelf->storeID    = $storeID;
        $wms_shelf->shelf_name = $shelf_name;

        if( !$G_PGLOB->DBCA->fetch($wms_shelf) ){
            echo json_encode( array('message'=>'该货位号['.$shelf_name.']不存在' , 'code'=>404 ) );
            return;
        }

        $shelfID = $wms_shelf->shelfID;

        //查询语句
        $sql_edit = "SELECT postID,goodsName,spec,product_code,goodsID,barcode FROM goods_sale_edit WHERE product_code=?";

        //联合外部编码表查询商品信息
        $external_search = 'SELECT gse.postID,gse.goodsName,gse.spec,gse.product_code,gse.goodsID,gse.barcode
                            FROM goods_sale_edit gse INNER JOIN goods_code gc ON gse.product_code = gc.product_code
                            WHERE gc.goodsCode=?';

        $resultGoods = $G_PGLOB->DBCA->stmt_query( $sql_edit , 's' , $goods );
        if( !$resultGoods ){

            $resultGoods = $G_PGLOB->DBCA->stmt_query( $external_search , 's' , $goods );

            if( !$resultGoods ){
                echo json_encode( array('message'=>'没有找到商品信息' , 'code'=>404 ) );
                return;
            }

        }

        //查询该货位是否已经与其他商品绑定
        $check_bangding = new entity('wms_store_shelf_goods');
        $check_bangding->shelfID = $shelfID;

        if( $G_PGLOB->DBCA->fetch($check_bangding) && $check_bangding->postID != $resultGoods[0]->postID ){
            echo json_encode( array('message'=>'该货位已与其他商品绑定' , 'code'=>400 ) );
            return;
        } else if ( $G_PGLOB->DBCA->fetch($check_bangding) && $check_bangding->postID == $resultGoods[0]->postID ){

            echo json_encode( array('message'=>'该货位已与该商品绑定' , 'code'=>400 ) );
            return;

        }

        //查询该商品是否已经与其他货位绑定
        $check_goods_bangding = new entity('wms_store_shelf_goods');
        $check_goods_bangding->postID = $resultGoods[0]->postID;

        if( $G_PGLOB->DBCA->fetch($check_goods_bangding) && $check_goods_bangding->shelfID != $shelfID ){
            echo json_encode( array('message'=>'该商品已与其他货位绑定<br>绑定货位为：<font style="font-weight:bold;">'.$check_goods_bangding->shelf_name.'</font>' , 'code'=>400 ) );
            return;
        }

        $wms_store_shelf_goods               = new entity('wms_store_shelf_goods');
        $wms_store_shelf_goods->storeID      = $storeID;
        $wms_store_shelf_goods->shelfID      = $shelfID;
        $wms_store_shelf_goods->postID       = $resultGoods[0]->postID;
        $wms_store_shelf_goods->creator      = $G_PGLOB->currentUserID;
        $wms_store_shelf_goods->shelf_name   = $shelf_name;
        $wms_store_shelf_goods->goods_name   = $resultGoods[0]->goodsName;
        $wms_store_shelf_goods->barcode      = $resultGoods[0]->barcode;
        $wms_store_shelf_goods->product_code = $resultGoods[0]->product_code;


        try{

            $G_PGLOB->DBCA->save($wms_store_shelf_goods);

            echo json_encode( array('message'=>'保存成功' , 'code'=>200 ) );
            return;

        }catch(Exception $e){

            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，保存失败' , 'code'=>500 ) );
            return;

        }

    }

    //货位管理列表
    function shelfManage(){

        global $G_PGLOB;

        //仓库类
        $wmsHandler = new wmsHandler($G_PGLOB->DBCA);

        if(isset($_REQUEST['storeID']) && $_REQUEST['storeID'] == -1 ){
            unset($_REQUEST['storeID']);
        }

        try {

            //查询
            $result = $wmsHandler->searchShelfGoods($_REQUEST);

            //组织返回的数据
            $result_array = array(
                'page'  => $_REQUEST['page'],
                'total' => $_REQUEST['count'],
                'rows'  => array()
            );

            if( $result ){

                foreach ( $result as $value){

                    $result_array['rows'][] = array(
                        'id' => $value['storeID'].'-'.$value['shelfID'].'-'.$value['postID'],
                        'cell' => array(
                            $value['storeName'],
                            $value['shelf_name'],
                            $value['product_code'],
                            $value['goods_name']
                        )
                    );

                }

            }

            echo json_encode($result_array);
            return;

        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }

    }

    //解除货位绑定
    function cancel_shelfBind(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        /**接收参数
         *
         * $_REQUEST[delArr] => Array(
        [0] => 12-19-864
        [1] => 18-20-765
        [2] => 17-27-876
        )
         *这是由“仓库号-货位号-商品网购号”组合成的字符串
         */
        $delArr = $_REQUEST['delArr'];

        //删除该仓库的库位信息
        $del_store_shelf_goods = 'DELETE FROM wms_store_shelf_goods WHERE storeID = ? AND shelfID = ? AND postID = ?';

        //统计不存在的货位绑定数目
        $errorNum_store = 0;
        $errorArr = array();

        if( $delArr ){

            //检查要删除的仓库是否全部存在
            foreach( $delArr as $value ){

                list($storeID , $shelfID , $postID ) = explode('-',$value);

                //信息是否存在
                $checkArr = array('storeID'=>$storeID,'shelfID'=>$shelfID,'postID'=>$postID);
                $result   = $commHandler->search($checkArr,'wms_store_shelf_goods');

                if( !$result ){
                    $errorArr[] = $value;
                    $errorNum_store++;
                }

            }

            if( $errorNum_store > 0 ){

                echo json_encode( array('message'=>'所选部分货位绑定已不存在，请刷新页面' , 'code'=>400 ) );
                return;

            }else{

                try{

                    //开启事务
                    $G_PGLOB->DBCA->beginTransaction();

                    //循环删除
                    foreach( $delArr as $value ){

                        list($storeID , $shelfID , $postID ) = explode('-',$value);

                        //解绑货位
                        $G_PGLOB->DBCA->stmt_query($del_store_shelf_goods , 'iii' , array($storeID,$shelfID,$postID) );

                    }

                    //提交事务
                    $G_PGLOB->DBCA->commit();

                    echo json_encode( array('message'=>'解绑成功', 'code'=>200) );
                    return;

                }catch( Exception $e ){

                    $G_PGLOB->DBCA->rollBack();
                    error_log($e->getMessage());
                    echo json_encode( array('message'=>'系统错误，请与管理员联系', 'code'=>500) );
                    return;

                }

            }

        }else{

            echo json_encode( array('message'=>'请选择要解绑的货位' , 'code'=>400 ) );
            return;

        }


    }


}